package com.iwords.android;

import java.util.UUID;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.text.ClipboardManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class IWords extends Activity {

	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// System.out.println("IWords.create().");
		autoLogin();// IWords.onCreate()
	}


	private void setPreviousUsername() {
		SharedPreferences settings = getSharedPreferences(this.getClass().getName(), MODE_PRIVATE);
		String username = settings.getString("username", null);
		//System.out.println("IWords.setPreviousUsername() username = "+username);
		//System.out.println("IWords.setPreviousUsername() this.getUUID() = "+this.getUUID());
		//System.out.println("IWords.setPreviousUsername() username.equals(this.getUUID()) = "+this.getUUID().equals(username));
		if (username != null && !this.getUUID().equals(username)){
			((EditText) findViewById(R.id.user_email)).setText(username);
			((Button) findViewById(R.id.silentlyRegister)).setVisibility(View.GONE);
		}
		
		String password = settings.getString("password", null);
		if (password != null && !this.getUUID().equals(username)){
			((EditText) findViewById(R.id.user_password)).setText(password);
		}
	}

	private boolean getAutoLogin() {
		SharedPreferences settings = getSharedPreferences(this.getClass().getName(), MODE_PRIVATE);
		boolean autologin = settings.getBoolean("autoLogin", true);
		return autologin;
	}
	
	private String getUUID(){
		final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
	    final String tmDevice, tmSerial, androidId;
	    tmDevice = "" + tm.getDeviceId();
	    tmSerial = "" + tm.getSimSerialNumber();
	    androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
	    UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
	    String deviceId = deviceUuid.toString();
	    //System.out.println("IWords.getUUID() deviceId = "+deviceId);
	    return deviceId;
	}
	
	public void copyQQ(View v){
		this.vibrate();
		ClipboardManager clipboardManager  = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
		clipboardManager.setText(((TextView)this.findViewById(R.id.qq_number)).getText());
		this.displayMessage("群号已复制到剪贴板。");
	}

    /**
     * 使用设备信息，自动注册一个账号。
     * １.　用户已经自动注册过，卸载后重新安装，又触发自动注册，注册会失败，可以尝试获取从前的历史数据
     * ２.　如果注册成功，则将注册信息保存在客户端，便于下次使用自动登录 
     */
	public void silentlyRegister(View view) {
		this.vibrate();
		String username = getUUID();
		String password = "password";
		if(login(username, password, false)){//先尝试登录
			
		}else if(register()){
			SharedPreferences settings = this.getSharedPreferences(IWords.class.getName(), MODE_PRIVATE);
			SharedPreferences.Editor editor = settings.edit();
			editor.putBoolean("autoLogin", true);
			editor.putString("username", username);
			editor.putString("password", password);
			editor.remove("currentlib");//新注册用户不应该有currentlib属性，移除这个属性，保证新注册用户可以进入词库课本选择界面
			editor.commit();  
			//当从旧用户注册新用户，重新开始时，需要清理掉上一个用户的驻留内存数据
			//WordsKnownManager.clear();
			IWordsApp iWordsApp = (IWordsApp) getApplicationContext();
			iWordsApp.clear();
			autoLogin();
		}else{//说明注册过，但本地没有用户信息，所以出现"不注册，先用用看"的按钮，此时应该从服务器端取用户信息
			//autoLogin();
		}
	}
	
	public boolean register(){
		String href = this.getResources().getString(R.string.user_register);
		
		//System.out.println("Register.valid()! href="+href);
		try {
			String paramStr = "&username="+getUUID();
			paramStr += "&password=password";
			// 有用户昵称不能为空的限制，先添加一个绕过
			paramStr += "&nickname=nickname";

			href = href  + paramStr;
			//System.out.println("Register.valid()! href="+href);
			HttpPost request = new HttpPost(href);

			// 发送请求
			HttpResponse httpResponse = new DefaultHttpClient().execute(request);
			// 得到应答的字符串，这也是 JSON 格式保存的数据	
			
			String retSrc = EntityUtils.toString(httpResponse.getEntity());
			//System.out.println("IWords.register() retSrc="+retSrc);
			retSrc = CodeUtils.decode(retSrc);
			//System.out.println("IWords.register() after decode retSrc="+retSrc);
			// 生成 JSON 对象
			JSONObject jSONObject = new JSONObject(retSrc);
			boolean success = jSONObject.getBoolean("isSuccess");
			return success;
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;	   
	}
	
	public void loginHandler(View view) {
		this.vibrate();
		// System.out.println("IWords.loginHandler() this.getParent() = "+this.getParent());
		// if(true) this.startActivity(new Intent(this, ShowWord.class));
		String email = ((EditText) findViewById(R.id.user_email)).getText().toString();
		String password = ((EditText) findViewById(R.id.user_password)).getText().toString();
		login(email, password, true);
	}

	public void registerHandler(View view) {
		this.vibrate();
		Intent intent = new Intent(this, Register.class);
		this.startActivity(intent);
		this.finish();
	}

	private void autoLogin() {
		setPreviousUsername();
		SharedPreferences settings = getSharedPreferences(this.getClass().getName(), MODE_PRIVATE);
		String username = settings.getString("username", null);
		String password = settings.getString("password", null);
		if (username == null || password == null)
			return;
		this.login(username, password, false);
	}

	private boolean login(String username, String password, boolean alert) {
		String href = this.getResources().getString(R.string.user_login);
		href += "&username=" + username;
		href += "&password=" + password;
		HttpPost request = new HttpPost(href);
		//System.out.println("IWords.login()! href=" + href);
		try {
			JSONObject jSONObject = ServerAccessor.access(this, request);
			boolean success = jSONObject.getBoolean("isSuccess");
			if (success) {
				JSONObject defaultValue = (JSONObject) jSONObject.getJSONObject("defaultValue");
				IWordsApp iWordsApp = (IWordsApp) getApplicationContext();
				iWordsApp.getUser().setUserid(defaultValue.getLong("userid"));
				iWordsApp.getUser().setEmail(defaultValue.getString("username"));
				iWordsApp.getUser().setNick(CodeUtils.decode(defaultValue.getString("nickname")));
				this.saveSettings(username, password, iWordsApp.getUser().getUserid());
				
				boolean canGo = true;
				if(defaultValue.has("currentlib") && defaultValue.getLong("currentlib")>0){
					//System.out.println("Splash.shoPayMe()! 用户在服务器上有currentlib信息，说明是老用户 need migration");
					long userid = defaultValue.getLong("userid");
					long currentlib = defaultValue.getLong("currentlib");
					this.showMigrationDialog(userid, currentlib);
					canGo = false;
				}else{
					//System.out.println("Splash.shoPayMe()! 不需要数据迁移，判断是否需要获取数据");
					//如果本地无数据且服务器上也没有这个用户的数据，就是新用户
					//如果本地无数据，但服务器上有这个用户的数据，先获取用户数据
					DBHelper dbHelper = new DBHelper(this);
					try{
						long userid = defaultValue.getLong("userid");
						DBHelper.UserLibs userLib = dbHelper.getCurrentLib(userid);
						if(userLib == null){//本地无数据
							//看服务器端有没有这个用户的数据
							if(this.hasHistory(userid)){
								//System.out.println("Splash.shoPayMe()! 用户在服务器上没有currentlib信息，本地没有数据，但是服务器上有这个用户的数据。");
								this.showSynchronizeDialog(userid, -1L);//新用户的currentlib没有在服务器端存储
								canGo = false;
							}
						}
					}finally{
						dbHelper.cleanup();
					}
				}

				// 判断是否有服务器端消息待处理
				//System.out.println("IWords.login() defaultValue.has(\"messageid\") = "+defaultValue.has("messageid"));
				if(canGo){
					if (defaultValue.has("messageid") && needShowMessage(defaultValue.getInt("messageid"))) {
						//如果有，启动显示消息的activity，关闭消息activity时，再执行启动背单词的逻辑
						Intent intent = new Intent(this, ShowNotify.class);
						intent.putExtra("messageid", defaultValue.getInt("messageid"));
						intent.putExtra("messagetype", defaultValue.getInt("messagetype"));
						intent.putExtra("message", defaultValue.getString("message"));
						this.startActivity(intent);
					} else {
						showWord();
					}
				}
				return true;
			} else {
				if(alert){
					this.displayMessage(CodeUtils.decode(jSONObject.getString("message")));
				}
			}
		} catch(NeedPayException ne){
			//System.out.println("*******NeedPayException catched. ");
			Intent intent = new Intent(this, com.iwords.android.AlipayActivity.class);
			this.startActivity(intent);
		} catch (Exception e) {
			//e.printStackTrace();
			this.displayMessage(e.getMessage());
		}
		return false;
	}
	private boolean hasHistory(long userid){
		boolean hasHistory = false;
		String href = this.getResources().getString(R.string.user_has_history);
		href += userid;
		HttpPost request = new HttpPost(href);
		//System.out.println("Splash.hasHistory()! href=" + href);
		try {
			JSONObject jSONObject = ServerAccessor.access(this, request);
			boolean success = jSONObject.getBoolean("isSuccess");
			if (success) {
				JSONObject defaultValue = (JSONObject) jSONObject.getJSONObject("defaultValue");
				if(defaultValue.has("hasHistory") && defaultValue.getBoolean("hasHistory")){
					//System.out.println("Splash.hasHistory() 获取历史数据");
					hasHistory = true;
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return hasHistory;
	}
	//新用户刷机或换设备后，需要重建数据
	private void showSynchronizeDialog(final long userid, final long currentlib) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle("提示");
		builder.setMessage("您本机上没有学习资料，但服务器有保存学习的历史记录，必须同步这些数据后，才能继续使用。");
			builder.setPositiveButton("现在开始同步", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					//数据迁移逻辑
					//System.out.println("Splash.showMigrationDialog() 数据同步：");
					Intent migrationIntent = new Intent(IWords.this, DataMigration.class);
					migrationIntent.putExtra("userid", userid);
					migrationIntent.putExtra("currentlib", currentlib);
					IWords.this.startActivity(migrationIntent);
				}
			});

		Dialog dialog = builder.setNegativeButton("放弃", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//System.out.println("Splash.showMigrationDialog() 放弃");
				IWords.this.finish();
			}
		}).create();
		//dialog.setCancelable(false);
		dialog.show();
	}

	//老用户升级到新版本，数据迁移提示
	private void showMigrationDialog(final long userid, final long currentlib) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle("提示");
		builder.setMessage("从版本1.5开始，将会把您正在记背的单词信息，记录在您的手持设备本地，从而大大提高操作流畅度。");
			builder.setPositiveButton("现在开始迁移", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					//数据迁移逻辑
					//System.out.println("Splash.showMigrationDialog() 数据迁移：");
					Intent migrationIntent = new Intent(IWords.this, DataMigration.class);
					migrationIntent.putExtra("userid", userid);
					migrationIntent.putExtra("currentlib", currentlib);
					IWords.this.startActivity(migrationIntent);
				}
			});

		Dialog dialog = builder.setNegativeButton("放弃", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//System.out.println("Splash.showMigrationDialog() 放弃");
				IWords.this.finish();
			}
		}).create();
		//dialog.setCancelable(false);
		dialog.show();
	}

	final static int PICK_WORD_LIB_REQUEST = 0;

	/**判断是否需要显示服务器端消息*/
	private boolean needShowMessage(int messageid){
		IWordsApp iWordsApp = (IWordsApp) getApplicationContext();
		SharedPreferences settings = this.getSharedPreferences(ShowNotify.class.getName(), MODE_PRIVATE);
		return settings.getBoolean(iWordsApp.getUser().getUserid()+"_showmessage_"+messageid, true);
	}

	/**
	 * 选择新课本，则意味着将所选对应课本的单词初始化到 用户的单词信息中，然后才进入背单词页面
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PICK_WORD_LIB_REQUEST) {
			if (resultCode == RESULT_OK) {
				// System.out.println("IWords.onActivityResult() data = " + data);
				Long libId = data.getLongExtra("selectedLibId", 0L);
				Boolean isLeaf = data.getBooleanExtra("isLeaf", Boolean.FALSE);
				if (isLeaf) {
					Intent intent = new Intent(this, DownloadWordsLib.class);
					intent.putExtra("currentWordLibId", libId);
					this.startActivity(intent);
				} else {
					Intent intent = new Intent(this, ShowWordLib.class);
					intent.putExtras(data);
					this.startActivityForResult(intent, PICK_WORD_LIB_REQUEST);
				}
			}
		}
	}

	private void showWord() {
		IWordsApp iWordsApp = (IWordsApp) getApplicationContext();
		long userid = iWordsApp.getUser().getUserid();
		DBHelper dbHelper = new DBHelper(this);
		try{
			DBHelper.UserLibs userLib = dbHelper.getCurrentLib(userid);
			if (userLib!=null) {
				// 如果用户已经选过词库，则跳转到记单词页面
				Intent intent = new Intent(this, ProgressingActivity.class);
				intent.putExtra("currentLibId", userLib.libid);
				this.startActivity(intent);
			} else {
				
				// System.out.println("登录成功，用户没有当前课本，跳转到课本选择页");
				// 如果用户没有选过词库，则跳转到选择词库界面
				Intent intent = new Intent(this, ShowWordLib.class);
				this.startActivityForResult(intent, PICK_WORD_LIB_REQUEST);
			}
		}finally{
			dbHelper.cleanup();
		}
	}

	private void saveSettings(String username, String password, Long userid) {
		SharedPreferences settings = this.getSharedPreferences(this.getClass().getName(), MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putBoolean("autoLogin", true);
		editor.putString("username", username);
		editor.putString("password", password);
		editor.putLong("userid", userid);
		editor.commit();
	}

	public void onWindowFocusChanged(boolean hasFocus) {
		// System.out.println("IWords.onWindowFocusChanged() hasFocus="+hasFocus);
		super.onWindowFocusChanged(hasFocus);
//		if (hasFocus) {
//			if (getAutoLogin()) {
//				this.setPreviousPassword();
//			} else {
//				((EditText) findViewById(R.id.user_password)).setText("");
//			}
//		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		// Group ID
		int groupId = 0;
		// The order position of the item
		int menuItemOrder = Menu.NONE;
		// Create the menu item and keep a reference to it.

		MenuItem menuItem = menu.add(groupId, R.integer.menu_item_iwords_profile, menuItemOrder,
				this.getString(R.string.menu_item_iwords_profile));
		menuItem.setIcon(this.getResources().getDrawable(R.drawable.menu_profile));
		menuItem = menu.add(groupId, R.integer.menu_item_iwords_brief, menuItemOrder,
				this.getString(R.string.menu_item_iwords_brief));
		menuItem.setIcon(this.getResources().getDrawable(R.drawable.menu_settings));
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.integer.menu_item_iwords_profile) {
			// System.out.println("个人信息");
			Intent intent = new Intent(this, Register.class);
			intent.putExtra("fromConfigMenu", true);
			this.startActivity(intent);
		} else if (item.getItemId() == R.integer.menu_item_iwords_brief) {
			// System.out.println("设置");
			Intent intent = new Intent(this, GuideBeginIWords.class);
			intent.putExtra("fromMenu", true);
			this.startActivity(intent);
		}
		return true;
	}
	
	private void vibrate(){
		Vibrator mVibrator = (Vibrator)getApplication().getSystemService(android.app.Service.VIBRATOR_SERVICE);
		mVibrator.vibrate(new long[]{50,50},-1);
	}

	private void displayMessage(String message) {
		Toast t1 = Toast.makeText(getApplication(), message, Toast.LENGTH_LONG * 4);
		t1.show();
	}
	
	public void onResume() {
		super.onResume(); 
		com.mobclick.android.MobclickAgent.onResume(this);
	}
	
	public void onPause() {
		super.onPause(); 
		com.mobclick.android.MobclickAgent.onPause(this);
	}

}